# Creare un abbonamento
## Introduzione
Per attivare una dilazione o un pagamento è necessario prima inviare una richiesta di dilazione, quindi reindirizzare l'utente al gateway di pagamento con l'identificativo della dilazione ricevuto, passando un URL di ritorno. Il gateway reindirizzerà all'URL inviato per gestire il ritorno del pagamento.
## Inviare una richiesta di abbonamento
### Richiesta Http
```bash
POST https://api.jatapay.it/scrivi_abbonamento
```
### Parametri

| Parametro | Richiesto | Tipo |  Descrizione |
| -------------- | -------------- | -------------- |-------------- |
| importo   | Sì |  int  | L'importo dell'abbonamento espresso in centesimi di Euro (Minimo 100)  |
|  callback_url  | Sì | string   |  Un URL valido per il ritorno del pagamento  |
|  descrizione_prodotto  | Sì | string   |  La descrizione del prodotto  |
|  cliente  | Sì | string   |  L'identificativo di un cliente esistente, oppure `open` per far compilare i dati al cliente sul gateway di pagamento  |
|  cadenza  | No | object   |  La cadenza dell'abbonamento, con `valore` e `periodo` (entrambi obbligatori)  |
|  data_inizio  | No | string   |  La data di inizio dell'abbonamento in formato `AAAA-MM-GG` (default: oggi)  |
|  tipo  | No | string   |  La tipologia dell'abbonamento  |
|  payment_method  | No | string   |  Il metodo di pagamento: `card` per il pagamento con carta, `sdd` per SEPA Direct Debit  |
|  external_vendor_id  | No | string   |  L'identificativo della pratica nel tuo gestionale  |
|  metadata  | No | object   |  Un oggetto di valori personalizzati restituito nelle risposte e nei webhook  |
|  note  | No | string   |  Delle note descrittive per l'abbonamento  |

#### Oggetto `cadenza`

| Parametro | Richiesto | Tipo |  Descrizione |
| -------------- | -------------- | -------------- |-------------- |
| valore   | Sì |  int  |  Quante volte il periodo si ripete tra un'addebito e il successivo   |
| periodo   | Sì |  string  |  L'unità di tempo della cadenza   |

**shell**

 ```bash
 curl "https://api.jatapay.it/scrivi_abbonamento" \
  -H "Authorization: Bearer IL_TOKEN_DI_ACCESSO" \
  -H "Content-Type: application/json" \
  -d '{
    "importo": 2000,
    "callback_url": "https://e-commerce.example.com/callback_url",
    "note": "Abbonamento per motivo esempio",
    "cliente": "open",
    "descrizione_prodotto": "Descrizione del prodotto"
  }'
```
**PHP**

 ```PHP
 $dati_abbonamento = array(
            'importo' => 2000, //Importo in centesimi di euro
            'callback_url' => 'https://e-commerce.example.com/callback_url',
            'note' => 'Dilazione per motivo esempio',
            'cliente' => 'open',
            'descrizione_prodotto' => 'Descrizione del prodotto'
          );

    $url = curl_init("https://api.jatapay.it/scrivi_abbonamento");
    $authorization = "Authorization: Bearer ".$token;
    curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($url, CURLOPT_POSTFIELDS, json_encode($dati_abbonamento));
    curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($url, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/json',
      'Content-Length: ' . strlen(json_encode($dati_abbonamento)),
      $authorization
    ));

    $result = curl_exec($url);

    $api_response = json_decode($result);

    curl_close($url);
```

**Python**

```python
import requests
import json

dati_abbonamento = {
    'importo': 2000,  # Importo in centesimi di euro
    'callback_url': 'https://e-commerce.example.com/callback_url',
    'note': 'Dilazione per motivo esempio',
    'cliente': 'open',
    'descrizione_prodotto': 'Descrizione del prodotto'
}

url = "https://api.jatapay.it/scrivi_abbonamento"
token = "your_access_token"  #  il tuo token
authorization = "Bearer " + token

headers = {
    'Content-Type': 'application/json',
    'Authorization': authorization
}

response = requests.post(url, data=json.dumps(dati_abbonamento), headers=headers)

api_response = response.json()

print(api_response)

```

**Node.js**

```javascript
const token = 'IL_TOKEN_DI_ACCESSO';

const body = {
  importo: 2000, // Importo in centesimi di euro
  callback_url: 'https://e-commerce.example.com/callback_url',
  note: 'Abbonamento per motivo esempio',
  cliente: 'open',
  descrizione_prodotto: 'Descrizione del prodotto'
};

const response = await fetch('https://api.jatapay.it/scrivi_abbonamento', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(body)
});

console.log(response.status, await response.json());
```

**Go**

```go
package main

import (
	"fmt"
	"io"
	"net/http"
	"strings"
)

func main() {
	const token = "IL_TOKEN_DI_ACCESSO"

	body := `{
  "importo": 2000,
  "callback_url": "https://e-commerce.example.com/callback_url",
  "note": "Abbonamento per motivo esempio",
  "cliente": "open",
  "descrizione_prodotto": "Descrizione del prodotto"
}`

	req, err := http.NewRequest("POST", "https://api.jatapay.it/scrivi_abbonamento", strings.NewReader(body))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+token)
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	data, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}

	fmt.Println(res.StatusCode, string(data))
}
```

**.NET**

```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        const string token = "IL_TOKEN_DI_ACCESSO";

        var body = """
            {
              "importo": 2000,
              "callback_url": "https://e-commerce.example.com/callback_url",
              "note": "Abbonamento per motivo esempio",
              "cliente": "open",
              "descrizione_prodotto": "Descrizione del prodotto"
            }
            """;

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        var content = new StringContent(body, Encoding.UTF8, "application/json");
        var response = await client.PostAsync("https://api.jatapay.it/scrivi_abbonamento", content);

        Console.WriteLine((int)response.StatusCode);
        Console.WriteLine(await response.Content.ReadAsStringAsync());
    }
}
```

**Java**

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String token = "IL_TOKEN_DI_ACCESSO";

        String body = """
                {
                  "importo": 2000,
                  "callback_url": "https://e-commerce.example.com/callback_url",
                  "note": "Abbonamento per motivo esempio",
                  "cliente": "open",
                  "descrizione_prodotto": "Descrizione del prodotto"
                }
                """;

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.jatapay.it/scrivi_abbonamento"))
                .header("Authorization", "Bearer " + token)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(body))
                .build();

        HttpResponse<String> response = HttpClient.newHttpClient()
                .send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.statusCode());
        System.out.println(response.body());
    }
}
```

Il comando ritornerà un JSON con questa struttura:

```json
{
    "app": false,
    "id_dilazione": "6aec4cd9010c3c59f018f590",
    "link_to_pay": false,
    "payment_url": "https://react.jatapay.it/gateway/6aec4cd9010c3c59f018f590"
}
```

### Risposta

| Campo | Tipo |  Descrizione |
| -------------- | -------------- |-------------- |
| app   | boolean |  Indica se la richiesta arriva da un client applicativo interno (flag riservato)   |
| id_dilazione   | string |  L'identificativo dell'abbonamento appena creato   |
| link_to_pay   | boolean |  Indica se l'abbonamento è stato creato come link di pagamento condivisibile   |
| payment_url   | string |  L'URL a cui reindirizzare l'utente per completare il pagamento   |

:::warning
La richiesta deve avere l'header Content-Type: application/json e includere il parametro nel corpo del JSON e l'header Authorization: Bearer token
:::

### Reindirizzare l'utente al gateway di pagamento

Una volta creato l'abbonamento bisogna reindirizzare l'utente all'URL restituito nel campo `payment_url` della risposta:

```bash
https://react.jatapay.it/gateway/ID_ABBONAMENTO
```

L'utente completerà il processo di pagamento e sarà reindirizzato all'url passato in precedenza.

### Gestire il ritorno del pagamento
In qualunque momento sarà possibile recuperare le informazioni sull'abbonamento per il controllo dell'avvenuta attivazione dello stesso. La risposta e tutti i campi restituiti sono descritti in [Dettaglio abbonamento](/riferimento-api/abbonamenti/dettaglio-abbonamento).

```bash
GET https://api.jatapay.it/abbonamenti/ID_ABBONAMENTO
```
:::warning
Sostituire ID_ABBONAMENTO con l'id ottenuto in precedenza
:::

**shell**

```shell
   curl "https://api.jatapay.it/abbonamenti/ID_ABBONAMENTO" \
 -H "Authorization: Bearer IL_TOKEN_DI_ACCESSO"
```
**PHP**

```php
$urlstring = "https://api.jatapay.it/abbonamenti/".$_GET['id_abbonamento'];
   $url = curl_init($urlstring);
   $authorization = "Authorization: Bearer ".$token;
   curl_setopt($url, CURLOPT_CUSTOMREQUEST, "GET");
   curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($url, CURLOPT_HTTPHEADER, array(
     $authorization
   ));

   $result = curl_exec($url);
   curl_close($url);
   $api_response = json_decode($result);
```
**Python**

```python
import requests
import cgi

form = cgi.FieldStorage()

id_abbonamento = form.getValue('id_abbonamento')
token = 'IL_TUO_TOKEN'
headers = {"Authorization": "Bearer " + token}
url = 'https://api.jatapay.it/abbonamenti/' + id_abbonamento
response = requests.get(url,headers=headers)
if response.status_code == 200:
  response = response.json()
else:
  print('Error, ' + str(response.status_code))
```
**Node.js**

```javascript
const token = 'IL_TOKEN_DI_ACCESSO';
const idAbbonamento = 'ID_ABBONAMENTO';

const response = await fetch(`https://api.jatapay.it/abbonamenti/${idAbbonamento}`, {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${token}`
  }
});

const data = await response.json();
console.log(response.status, data);
```

**Go**

```go
package main

import (
	"fmt"
	"io"
	"net/http"
)

func main() {
	const token = "IL_TOKEN_DI_ACCESSO"
	idAbbonamento := "ID_ABBONAMENTO"

	req, err := http.NewRequest("GET", "https://api.jatapay.it/abbonamenti/"+idAbbonamento, nil)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+token)

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	data, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}

	fmt.Println(res.StatusCode, string(data))
}
```

**.NET**

```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        const string token = "IL_TOKEN_DI_ACCESSO";
        const string idAbbonamento = "ID_ABBONAMENTO";

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        var response = await client.GetAsync($"https://api.jatapay.it/abbonamenti/{idAbbonamento}");

        Console.WriteLine((int)response.StatusCode);
        Console.WriteLine(await response.Content.ReadAsStringAsync());
    }
}
```

**Java**

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String token = "IL_TOKEN_DI_ACCESSO";
        String idAbbonamento = "ID_ABBONAMENTO";

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.jatapay.it/abbonamenti/" + idAbbonamento))
                .header("Authorization", "Bearer " + token)
                .GET()
                .build();

        HttpResponse<String> response = HttpClient.newHttpClient()
                .send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.statusCode());
        System.out.println(response.body());
    }
}
```

Il comando ritornerà un JSON con questa struttura:

```json
{
  "_id": "65b279426d2f219d702a7f69",
  "callback_url": "https://e-commerce.example.com/callback_url",
  "client": "JataPay",
  "cliente": "open",
  "data_inizio": "Thu, 25 Jan 2024 15:07:46 GMT",
  "data_inserimento": "Thu, 25 Jan 2024 15:07:46 GMT",
  "esercente': '60c5d53a052bf51a1ca1e1b5",
  "importo": 2000,
  "note": "Dilazione per motivo esempio",
  "numero": 170,
  "numero_txt": "170",
  "stato": "iniziata",
  "user": "60c5d53a052bf51a1ca1e1b5"
}
```

#### Ricevere il webhook

In alternativa al polling puoi ricevere una notifica HTTP `POST` quando lo stato cambia, senza dover interrogare le API.

Il webhook si configura dalla Dashboard nella sezione **[Sviluppatori](https://dashboard.jatapay.it/sviluppatori)** oppure via API con l'endpoint `POST /esercente/developer_options` (vedi [Opzioni sviluppatore](/riferimento-api/opzioni-sviluppatore)).

Ogni notifica è firmata con il `webhook_secret` dell'esercente: vedi [Webhook](/riferimento-api/opzioni-sviluppatore/webhook) per il calcolo e la verifica della firma in tutti i linguaggi.
